<?php

include '../DB/db.php';
include '../class/UserClass.php';



// if the user logs in:
if (isset($_POST['login']) && $_POST['login']) {
    $row = getMyUserData();                         // get all data about the user.
    if ($row) {                                     // if user is in database:
        $user->doLogin($row['uid'], $row['type']);      // login the user.
        if ($row['type'] == 'administrator') {
            header("Location: /adminViews/myAdminSite.php");          // redirect to myAdminSite.php.
        } else if ($row['type'] == 'employee') {
            header("Location: /Views/myEmpSite.php");          // redirect to mySite.php.
        } else {
            header("Location: /Views/mySite.php");          // redirect to mySite.php.
        }
    } else {                                          // if user is not in db:
        echo "feil brukernavn eller passord!";          // error-message.
    }
} else if (isset($_REQUEST['userID'])) {
    $user->doLogin($_REQUEST['userID'], 'user');
    header("Location: /Views/mySite.php");
}
// if the user logs out:
else if (isset($_POST['logout']) && $_POST['logout']) {
    $user->logOut();                                // log user out
    header("Location: /index.php");                 // redirect to index.php
}
// if something went wrong:
else
    echo "Illegal action!";

function getMyUserData() {
    // returns all information in db about the current user:
    global $db;
    $pwd = md5($_POST['password']);         // Get and crypt the posted password.
    $username = $_POST['username'];         // Get the posted username.
    $sql = 'SELECT * FROM users WHERE email=:email AND password=:pwd';  // db query.
    $sth = $db->prepare($sql);              // Prepare $sql to be executed.
    $sth->bindParam(':pwd', $pwd);          // Copy $pwd to the word :pwd.
    $sth->bindParam(':email', $username);   // Copy $username to the word :email
    $sth->execute();                        // Execute the db query.
    $row = $sth->fetch();                   // Fetch all data in array $row.
    return $row;                            // return array with data.
}

?>
